<?php


namespace App\Admin\Actions\BatchAction;


use App\Admin\Actions\BatchAction;
use App\Models\AdminUser;
use App\PatentApply;
use App\Setting;
use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class BatchPatentApplyReview extends BatchAction
{
    public $name = '批量审批';

    public function handle(Collection $collection, Request $request)
    {
        $status = $request->get('status');
        $remark = $request->get('remark') ?: '';
        $review_name = Setting::getReviewName(1);
        $user = Admin::user();
        $collection = $collection->filter(function ($item) {
            return $item instanceof PatentApply && !$item['review_status'];
        })->values();
        try {
            foreach ($collection as $model) {
                $model->review_status = $status;
                $model->review_remark = $remark;
                $model->save();
                $model->remarks()->create([
                    'name' => $review_name . '-' . data_get([1 => '同意申请', 2 => '不同意申请', 3 => '退回修改'], $status),
                    'user_id' => $user->id,
                    'remark' => $remark
                ]);
            }
        } catch (\Exception $exception) {
            return $this->response()->swal()->error('操作失败！')->refresh();
        }
        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $this->radio('status', '审核')->options([1 => '同意申请', 2 => '不同意申请', 3 => '退回修改'])->required();
        $this->textarea('remark', '备注');
    }

    public function authorize(AdminUser $user, Collection $collection)
    {
        return $user->role_type == 1;
    }


}
